package com.itheima.demo1;

import java.util.HashSet;
import java.util.Set;
// 定义链表节点类
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<ListNode> visited = new HashSet<ListNode>();
        ListNode temp = headA;
        while (temp != null) {
            visited.add(temp);
            temp = temp.next;
        }
        temp = headB;
        while (temp != null) {
            if (visited.contains(temp)) {
                return temp;
            }
            temp = temp.next;
        }
        return null;
    }
    public static void main(String[] args) {
        // 创建链表 A: 1 -> 2 -> 3 -> 6 -> 7
        ListNode nodeA1 = new ListNode(1);
        ListNode nodeA2 = new ListNode(2);
        ListNode nodeA3 = new ListNode(3);
        nodeA1.next = nodeA2;
        nodeA2.next = nodeA3;

        // 创建链表 B: 4 -> 5 -> 6 -> 7
        ListNode nodeB1 = new ListNode(4);
        ListNode nodeB2 = new ListNode(5);
        nodeB1.next = nodeB2;

        // 创建公共部分 6 -> 7
        ListNode nodeCommon1 = new ListNode(6);
        ListNode nodeCommon2 = new ListNode(7);
        nodeA3.next = nodeCommon1;
        nodeB2.next = nodeCommon1;
        nodeCommon1.next = nodeCommon2;

        Solution solution = new Solution();
        ListNode intersectionNode = solution.getIntersectionNode(nodeA1, nodeB1);
        if (intersectionNode != null) {
            System.out.println("两个链表的第一个相交节点的值是: " + intersectionNode.val);
        } else {
            System.out.println("两个链表没有相交节点");
        }
    }

}
